<template>
  <div>
    <!--  主评论输入区，获得焦点可以显示提交按钮  -->
    <div v-clickoutside="hideReplyBtn" @click="inputFocus" class="my-reply">
      <div class="reply-info">
        <div
          tabindex="0"
          contenteditable="true"
          id="replyInput"
          spellcheck="false"
          placeholder="输入评论..."
          class="reply-input"
          @focus="showReplyBtn"
          @input="onDivInput($event)"
        >
        </div>
        <div class="reply-btn-box" v-show="btnShow">
          <el-button class="reply-btn" size="medium" @click="sendComment" type="primary">发表评论</el-button>
        </div>
      </div>
    </div>
    <!-- 主评论区，显示主评论   -->
    <div v-for="(item,i) in comments" :key="i" class="author-title reply-father">
      <div class="author-info">
        <span class="author-name">{{ item.username }}</span>
        <span class="author-time">{{ item.date }}</span>
      </div>
      <div class="icon-btn">
        <span @click="showReplyInput(i,item)"><i
          class="iconfont el-icon-s-comment"></i>{{ item.reviewList.length }}</span>
        <span @click="deleteComment(item)" v-if="(item.id===$store.state.id&&$store.state.authority===2)||$store.state.authority===4"><i
          class="iconfont el-icon-delete-solid"></i></span>
      </div>
      <div class="talk-box">
        <p>
          <span class="reply">{{ item.content }}</span>
        </p>
      </div>

      <!--   子评论区   -->
      <div class="reply-box">
        <div v-for="(reply,j) in item.reviewList" :key="j" class="author-title">
          <div class="author-info">
            <span class="author-name">{{ reply.username }}</span>
            <span class="author-time">{{ reply.date }}</span>
          </div>
          <div class="icon-btn">
            <span @click="showReplyInput(i,reply)"><i
              class="iconfont el-icon-s-comment"></i></span>
            <span @click="deleteComment(reply)" v-if="(reply.id===$store.state.id&&$store.state.authority===2)||$store.state.authority===4"><i
              class="iconfont el-icon-delete-solid"></i></span>
          </div>
          <div class="talk-box">
            <p>
              <span>回复 {{ reply.userReviewed }}:</span>
              <span class="reply">{{ reply.content }}</span>
            </p>
          </div>
          <div class="reply-box">

          </div>
        </div>
      </div>
      <div v-show="showInput[i]" class="my-reply my-comment-reply">
        <div class="reply-info">
          <div tabindex="0" contenteditable="true" spellcheck="false" placeholder="输入评论..." @input="onDivInput($event)"
               class="reply-input reply-comment-input"></div>
        </div>
        <div class=" reply-btn-box">
          <el-button class="reply-btn" size="medium" @click="sendCommentReply(item)" type="primary">发表评论</el-button>
        </div>
      </div>
    </div>
    <el-empty v-if="comments.length===0" description="还没有评论哦">
    </el-empty>
    <el-row>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="comments.length"
        class="pagination">
      </el-pagination>
    </el-row>
  </div>
</template>

<script>

const clickoutside = {
  // 初始化指令
  bind(el, binding, vnode) {
    function documentHandler(e) {
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false;
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
        binding.value(e);
      }
    }

    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.vueClickOutside = documentHandler;
    document.addEventListener('click', documentHandler);
  },
  update() {
  },
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener('click', el.vueClickOutside);
    delete el.vueClickOutside;
  },
};
export default {
  name: "Comment",
  props: {
    noteId: {
      type: Number,
      default: () => {
        return 0
      }
    }
  },
  data() {
    return {
      btnShow: false,
      //笔记id
      id:this.noteId,
      //页码
      currentPage: 1,
      pageSize: 15,
      //评论索引
      index: 0,
      //评论内容
      replyComment: '',
      myName: this.$store.state.username,
      myId: this.$store.state.id,
      review:{},
      comments: [],
      showInput:[]
    }
  },
  directives: {clickoutside},
  methods: {
    messageTitleClick(num) { // 点击了具体某条消息
      console.log("点击了消息", num);
    },

    //展示类

    //获得主评论的焦点
    inputFocus() {
      var replyInput = document.getElementById('replyInput');
      replyInput.style.padding = "8px 8px"
      replyInput.style.border = "2px solid blue"
      replyInput.focus()
    },
    //展示主评论的提交按钮
    showReplyBtn() {
      this.btnShow = true
    },
    //失去焦点时隐藏主评论的按钮
    hideReplyBtn() {
      let replyInput = document.getElementById('replyInput')
      this.btnShow = false
      replyInput.style.padding = "10px"
      replyInput.style.border = "none"
    },
    //展示回复的input
    showReplyInput(i,review) {
      // this.comments[this.index].inputShow = false
      this.$set(this.showInput,this.index,false)
      this.index = i
      // this.comments[i].inputShow = true
      this.$set(this.showInput,i,true)
      this.review=review
    },


    //提交类
    /*
      获得所有评论
     */
    getComment(){
      this.$axios.get(`/comment/getAll/noteId=${this.id}/parentId=-1/page=${this.currentPage-1}`)
        .then(res=>{
          this.comments=res.data.data
          this.comments.forEach((item)=>{
            this.showInput.push(false)
          })
        }).catch(failRes=>{console.log(failRes)})
    },

    /*
      发送评论
     */
    sendComment() {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '评论不能为空'
        })
      } else {
        this.$axios.post('/comment/add', {
          noteId: this.noteId,
          parentId: -1,
          reviewId: null,
          content:this.replyComment,
          date:this.currentDate()
        }).then(() => {
          this.getComment()
        }).catch(failRes => console.log(failRes))
      }
    },
    sendCommentReply(parent) {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '评论不能为空'
        })
      } else {
        this.$axios.post('/comment/add', {
          id: this.myId,
          noteId: this.noteId,
          parentId: parent.commentId,
          reviewId: this.review.commentId,
          content:this.replyComment,
          date:this.currentDate()
        }).then(() => {
          this.getComment()
        }).catch(failRes => console.log(failRes))
      }
    },

    //删除
    /*
      删除评论
     */
    deleteComment(item){
      this.$confirm('此操作将删除评论, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.get(`/comment/delete/commentId=${item.commentId}`).then(()=>{
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getComment()
        }).catch(failRes=>{
          console.log(failRes)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    /*
    加载时间
     */
    currentDate() {
      let d = new Date();
      let year = d.getFullYear();
      let month = d.getMonth();
      month = month + 1 > 12 ? 1 : month + 1;
      month = month > 9 ? month : "0" + month.toString();
      let day = d.getDate();
      day=day>9?day:"0"+day.toString();
      let hour = d.getHours();
      hour = hour > 9 ? hour : "0" + hour.toString();
      let minute = d.getMinutes();
      minute = minute > 9 ? minute : "0" + minute.toString();
      let second = d.getSeconds();
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },

    //分页类
    /*
      处理页码
     */
    handleCurrentChange(page) {
      this.currentPage = page
      this.getComment()
    },

    onDivInput: function (e) {
      this.replyComment = e.target.innerHTML;
    },
  },
  watch: {
    'id':{
      handler(newVal) {
        this.id = newVal
        this.getComment()
      },
      immediate:true
    }
  },
}
</script>

<style scoped lang="css">
.my-reply {
  padding: 10px;
  background-color: #fafbfc;
}

.my-reply .header-img {
  display: inline-block;
  vertical-align: top;
}

.my-reply .reply-info {
  display: inline-block;
  margin-left: 5px;
  width: 90%;
}

@media screen and (max-width: 1200px) {
  .my-reply .reply-info {
    width: 80%;
  }
}

.my-reply .reply-info .reply-input {
  min-height: 20px;
  line-height: 22px;
  padding: 10px 10px;
  color: #ccc;
  background-color: #fff;
  border-radius: 5px;
  width: 80%;
  display: inline-block;
}

.my-reply .reply-info .reply-input:empty:before {
  content: attr(placeholder);
}

.my-reply .reply-info .reply-input:focus:before {
  content: none;
}

.my-reply .reply-info .reply-input:focus {
  padding: 8px 8px;
  border: 2px solid #00f;
  box-shadow: none;
  outline: none;
}

.my-reply .reply-info .reply-btn-box {
  height: 20px;
  margin: 15px 0 0 0;
  display: inline-block;
}

.my-reply .reply-info .reply-btn-box .reply-btn {
  position: relative;
  float: right;
  margin-right: 0px;
}

.my-comment-reply {
  margin-left: 50px;
  display: flex;
  flex-direction: row;
}

.my-comment-reply .reply-input {
  width: 80%;
}

.author-title:not(:last-child) {
  border-bottom: 1px solid rgba(178, 186, 194, 0.3);
}

.author-title {
  margin-top: 1rem;
  padding: 10px;
}

.author-title .header-img {
  display: inline-block;
  vertical-align: top;
}

.author-title .author-info {
  display: inline-block;
  margin-left: 5px;
  width: 60%;
  height: 40px;
  line-height: 20px;
  display: flex;
  right: 10%
}

.author-title .author-info > span {
  display: block;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.author-title .author-info .author-name {
  color: #000;
  font-size: 18px;
  font-weight: bold;
  display: inline-block;
}

.author-title .author-info .author-time {
  font-size: 14px;
  margin-left: 20px;
  display: inline-block;
}

.author-title .icon-btn {
  width: 30%;
  padding: 0 !important;
  float: right;
}

@media screen and (max-width: 1200px) {
  .author-title .icon-btn {
    width: 20%;
    padding: 7px;
  }
}

.author-title .icon-btn > span {
  cursor: pointer;
}

.author-title .icon-btn .iconfont {
  margin: 0 5px;
}

.author-title .talk-box {
  margin: 0 50px;
}

.author-title .talk-box > p {
  margin: 0;
}

.author-title .talk-box .reply {
  font-size: 16px;
  color: #000;
}

.author-title .reply-box {
  margin: 10px 0 0 50px;
  background-color: #efefef;
}
</style>
